package com.qiang.test06;

import java.lang.reflect.Field;

public class Demo01 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        //创建类
        Class sc = Class.forName("com.qiang.test06.Student");
        //Method01(sc);
        //Method02(sc);
        //Method03(sc);
        //Method04(sc);
        //Method05(sc);

        //给成员变量赋值
        //Method06(sc);

        //给年龄赋值
        //Method07(sc);

        //给钱赋值
        Method08(sc);

        //获取成员变量

    }

    public static void Method08(Class sc) throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        //获取钱的变量
        Field money = sc.getDeclaredField("money");

        //创建学生对象
        Student student = (Student) sc.newInstance();

        //给钱赋值
        money.setAccessible(true);

        //money.set(student, 100000);
        Object o = money.get(student);
        System.out.println(o);
        System.out.println(student);
    }

    public static void Method07(Class sc) throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        Field age = sc.getField("age");

        //创建学生对象
        Student stu = (Student) sc.newInstance();

        //给年龄赋值

        age.set(stu, 23);
        System.out.println(stu);
    }

    public static void Method06(Class sc) throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        Field name = sc.getField("name");

        //创建学生对象
        Student student = (Student) sc.newInstance();

        //给成员变量赋值
        name.set(student, "张三");
        System.out.println(student);
    }

    public static void Method05(Class sc) throws NoSuchFieldException {
        //获取私有成员变量
        Field money = sc.getDeclaredField("money");
        System.out.println(money);
    }

    public static void Method04(Class sc) throws NoSuchFieldException {
        //获取年龄
        Field age = sc.getField("age");
        System.out.println(age);
    }

    public static void Method03(Class sc) throws NoSuchFieldException {
        //获取单个的公共成员变量
        Field name = sc.getField("name");
        System.out.println(name);
    }

    public static void Method02(Class sc) {
        //获取所有的成员变量
        Field[] dd = sc.getDeclaredFields();
        for (Field field : dd) {
            System.out.println(field);
        }
    }

    public static void Method01(Class sc) {
        //获取所有的公共成员变量
        Field[] f1 = sc.getFields();
        for (Field field : f1) {
            System.out.println(field);
        }
    }
}
